/**
 * 
 */
package com.maywide.jdp.system.bean;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.maywide.jdp.core.exception.AppException;
import com.maywide.jdp.core.vo.Page;
import com.maywide.jdp.dao.Dao;
import com.maywide.jdp.dao.PageQueryTemplate;
import com.maywide.jdp.system.entities.Module;
import com.maywide.jdp.system.vo.ModuleCheckedTree;
import com.maywide.jdp.system.vo.ModuleTree;

/**
 * 子系统管理Bean
 * 
 * @author luoyang
 * @version 1.0
 * @since JDK1.6
 */
@Component("moduleBean")
@Transactional(propagation = Propagation.REQUIRED)
public class ModuleBeanImpl implements ModuleBean {
	/**
	 * 基础DAO
	 */
	private Dao dao = null;

	/**
	 * @param dao
	 *            the dao to set
	 */
	@Autowired
	public void setDao(Dao dao) {
		this.dao = dao;
	}

	@Override
	public void insert(Object obj) throws Exception {
		Module module = (Module) obj;
		module.refreshPath();
		dao.insert(module);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void remove(Class clazz,Serializable id) throws Exception {
		Object obj = dao.find(clazz, id);
		dao.remove(obj);
	}

	@Override
	public void update(Object obj) throws Exception {
		Module module = (Module) obj;
		boolean flag = isDiffPath(module);
		if (flag)
			module.refreshPath();
		dao.update(module);
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public Object load(Serializable id) throws Exception {
		Module module = dao.find(Module.class, id);
		return module;
	}

	@Override
	public void lock(String id) throws Exception {
		String jql = "update Module as o set o.active = false where o.id = :id";
		Query query = dao.createQuery(jql);
		query.setParameter("id", id);
		query.executeUpdate();
	}

	@Override
	public void lockAll(String[] ids) throws Exception {
		String hql = "update Module as o set o.active = false where o.id in (:ids)";
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("ids", ids);
		dao.executeUpdate(hql, conditions);
	}

	@Override
	public void unlock(String id) throws Exception {
		String jql = "update Module as o set o.active = true where o.id = :id";
		Query query = dao.createQuery(jql);
		query.setParameter("id", id);
		query.executeUpdate();
	}

	@Override
	public void unlockAll(String[] ids) throws Exception {
		String hql = "update Module as o set o.active = true where o.id in (:ids)";
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("ids", ids);
		dao.executeUpdate(hql, conditions);
	}

	@Override
	public void move(String id, String parentID) throws Exception {
		String jql = "update Module as o set o.parent.id = :parentID where o.id = :id";
		Query query = dao.createQuery(jql);
		int row = 0;
		query.setParameter("id", id);
		query.setParameter("parentID", parentID);
		row = query.executeUpdate();
		if (row <= 0)
			throw new AppException("未发生移动操作!");
	}

	@Override
	public void move(List<String> ids, String parentID) throws Exception {
		int row = 0;
		String hql = "update Module as o set o.parent.id = :parentID where o.id in (:ids)";
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("ids", ids);
		conditions.put("parentID", parentID);
		row = dao.executeUpdate(hql, conditions);
		if (row <= 0)
			throw new AppException("未发生移动操作!");
	}

	@SuppressWarnings({ "rawtypes" })
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List tree(Map<String, Object> parameters) throws Exception {
		StringBuffer buf = new StringBuffer()
		.append("select distinct o.ID as id,")
		.append("o.MOD_CODE as code,")
		.append("o.MOD_NAME as name,")
		.append("o.MOD_NAME as text,")
		.append("o.MOD_PARENT_ID as parentID,")
		.append("o.MOD_DESC as description,")
		.append("o.MOD_ACTIVE as active,")
		.append("decode(sign(count(sub.ID)),1,0,1) as leaf")
		.append(" from SYS_MODULE o")
		.append(" left join")
		.append(" SYS_MODULE sub on o.ID = sub.MOD_PARENT_ID")
		.append(" INNER JOIN SYS_MODULE_ROLE_REL rel")
		.append(" ON o.ID         = rel.MOD_ID")
		.append(" INNER JOIN SYS_ROLE r")
		.append(" ON r.ID         = rel.ROLE_ID ");
		if (parameters.containsKey("roleIDs")) {
			String[] roleIDs = (String[]) parameters.get("roleIDs");
			if (roleIDs != null && roleIDs.length > 0) {
				buf.append(" AND r.ID IN (:roleIDs)");
			}
		}
		buf.append(" WHERE");
		if (parameters.containsKey("parentID"))
			buf.append(" o.ID IN(SELECT org.ID FROM SYS_MODULE org WHERE org.MOD_PARENT_ID = :parentID AND org.MOD_ACTIVE = 1)");
		else if(parameters.containsKey("rootID"))
			buf.append(" o.ID = :rootID");
		else
			buf.append(" o.ID IN(SELECT org.ID FROM SYS_MODULE org WHERE org.MOD_PARENT_ID IS NULL AND org.MOD_ACTIVE = 1)");
		buf.append(" AND");
		buf.append(" o.MOD_ACTIVE = 1 and o.REMOVED = 0");
		buf.append(" group by o.ID,o.MOD_CODE,o.MOD_NAME,o.MOD_PARENT_ID,o.MOD_DESC,o.MOD_ACTIVE");

		String sql = buf.toString();
		return dao.executeNativeQuery(sql, parameters, ModuleTree.class,
				"com.maywide.jdp.system.entities.Module.moduleTree");
	}
	
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<ModuleCheckedTree> treeGrid(Map<String, Object> parameters) throws Exception {
		StringBuffer buf = new StringBuffer()
		.append("select distinct o.ID as id,")
		.append("o.MOD_CODE as code,")
		.append("o.MOD_NAME as name,")
		.append("o.MOD_NAME as text,")
		.append("o.MOD_PARENT_ID as parentID,")
		.append("o.MOD_DESC as description,")
		.append("0 as checked,")
		.append("o.MOD_ACTIVE as active,")
		.append("decode(sign(count(sub.ID)),1,0,1) as leaf")
		.append(" from SYS_MODULE o")
		.append(" left join")
		.append(" SYS_MODULE sub on o.ID = sub.MOD_PARENT_ID")
		.append(" INNER JOIN SYS_MODULE_ROLE_REL rel")
		.append(" ON o.ID         = rel.MOD_ID")
		.append(" INNER JOIN SYS_ROLE r")
		.append(" ON r.ID         = rel.ROLE_ID ");
		if (parameters.containsKey("roleIDs")) {
			String[] roleIDs = (String[]) parameters.get("roleIDs");
			if (roleIDs != null && roleIDs.length > 0) {
				buf.append(" AND r.ID IN (:roleIDs)");
			}
		}
		buf.append(" WHERE");
		if (parameters.containsKey("parentID"))
			buf.append(" o.ID IN(SELECT org.ID FROM SYS_MODULE org WHERE org.MOD_PARENT_ID = :parentID AND org.MOD_ACTIVE = 1)");
		else if(parameters.containsKey("rootID"))
			buf.append(" o.ID = :rootID");
		else
			buf.append(" o.ID IN(SELECT org.ID FROM SYS_MODULE org WHERE org.MOD_PARENT_ID IS NULL AND org.MOD_ACTIVE = 1)");
		buf.append(" AND");
		buf.append(" o.MOD_ACTIVE = 1 and o.REMOVED = 0");
		buf.append(" group by o.ID,o.MOD_CODE,o.MOD_NAME,o.MOD_PARENT_ID,o.MOD_DESC,o.MOD_ACTIVE");

		String sql = buf.toString();
		List<ModuleCheckedTree> list = null;
		list = dao.executeNativeQuery(sql, parameters, ModuleCheckedTree.class,
				"com.maywide.jdp.system.entities.Module.moduleCheckedTree");
		
		buf = new StringBuffer()
		.append("select distinct o.ID as id,")
		.append("o.MOD_CODE as code,")
		.append("o.MOD_NAME as name,")
		.append("o.MOD_NAME as text,")
		.append("o.MOD_PARENT_ID as parentID,")
		.append("o.MOD_DESC as description,")
		.append("1 as checked,")
		.append("o.MOD_ACTIVE as active,")
		.append("decode(sign(count(sub.ID)),1,0,1) as leaf")
		.append(" from SYS_MODULE o")
		.append(" left join")
		.append(" SYS_MODULE sub on o.ID = sub.MOD_PARENT_ID")
		.append(" INNER JOIN SYS_MODULE_ROLE_REL rel")
		.append(" ON o.ID         = rel.MOD_ID")
		.append(" INNER JOIN SYS_ROLE r")
		.append(" ON r.ID         = rel.ROLE_ID ");
		if (parameters.containsKey("roleID")) {
			buf.append(" AND r.ID = :roleID");
		}
		buf.append(" WHERE");
		if (parameters.containsKey("parentID"))
			buf.append(" o.ID IN(SELECT org.ID FROM SYS_MODULE org WHERE org.MOD_PARENT_ID = :parentID AND org.MOD_ACTIVE = 1)");
		else if(parameters.containsKey("rootID"))
			buf.append(" o.ID = :rootID");
		else
			buf.append(" o.ID IN(SELECT org.ID FROM SYS_MODULE org WHERE org.MOD_PARENT_ID IS NULL AND org.MOD_ACTIVE = 1)");
		buf.append(" AND");
		buf.append(" o.MOD_ACTIVE = 1 and o.REMOVED = 0");
		buf.append(" group by o.ID,o.MOD_CODE,o.MOD_NAME,o.MOD_PARENT_ID,o.MOD_DESC,o.MOD_ACTIVE");

		sql = buf.toString();
		List<ModuleCheckedTree> checkedList = dao.executeNativeQuery(sql, parameters, ModuleCheckedTree.class,
				"com.maywide.jdp.system.entities.Module.moduleCheckedTree");
		if(checkedList != null && !checkedList.isEmpty()) {
			for(ModuleCheckedTree checkedModule : checkedList) {
				if(list.contains(checkedModule)) {
					list.remove(checkedModule);
					list.add(checkedModule);
				}
			}
		}
		
		return list;
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public Page page(int first, int limit, String sort, String dir,
			Map<String, Object> conditions, Map<String, Object> parameters)
			throws Exception {
		Page page = null;

		String queryString = "select o from Module as o inner join o.roles as r";
		String countQueryString = "select count(o.id) from Module as o inner join o.roles as r";
		if(conditions == null)
			conditions = new HashMap<String,Object>();
		if(!conditions.containsKey("parentID"))
			conditions.put("noParentID", null);
		PageQueryTemplate template = new PageQueryTemplate(queryString,
				countQueryString, first, limit, sort, dir);
		page = dao.executePageQuery(template, conditions, null);

		return page;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<ModuleTree> findSubTrees(Map<String, Object> conditions)
			throws Exception {
		String name = "com.maywide.jdp.system.entities.Menu.findMenus";
		List<ModuleTree> list = null;
		list = dao.executeNamedQuery(name, conditions, null,
				ModuleTree.class);
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<Module> findModules(String id) throws Exception {
		String name = "";
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("roleID", id);
		return dao.executeNamedQuery(name, null, parameters);
	}

	/**
	 * 判断是否改变了模块路径
	 * 
	 * @param org
	 */
	private boolean isDiffPath(Module module) throws Exception {
		String path = module.getPath();
		String refreshPath = module.getRefreshPath();
		return !refreshPath.equals(path);
	}
}
